package com.pl.redission;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.util.stream.Collectors;

/**
 * Date            Author           Version
 * 2022/1/27 15:21  pengli         1.0
 */
@Configuration
@ComponentScan
public class RedissionConfiguration {

    @Autowired
    private RedisProperties redisProperties;


    @Bean(destroyMethod="shutdown")
    public RedissonClient redissonClient() {
        Config config = new Config();

        RedisProperties.Cluster cluster = redisProperties.getCluster();
        String password = redisProperties.getPassword();
        if (cluster != null) {
            String[] nodes = cluster.getNodes().stream().map(node -> "redis://" + node).collect(Collectors.toList()).toArray(new String[0]);
            ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(nodes);
            if (StringUtils.hasText(password)) {
                clusterServersConfig.setPassword(password);
            }
        } else {
            SingleServerConfig singleServerConfig = config.useSingleServer().setAddress("redis://" + redisProperties.getHost()
                    + ":" + redisProperties.getPort());
            if (StringUtils.hasText(password)) {
                singleServerConfig.setPassword(password);
            }
        }

        return Redisson.create(config);
    }

}
